package com.oj.service.impl;

import com.oj.entity.Message;
import com.oj.entity.User;
import com.oj.mapper.MessageMapper;
import com.oj.service.MessageService;
import com.oj.service.UserService;
import com.oj.util.IpUtil;
import com.oj.util.MyFreeMarker;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserService userService;

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    public void topTopicsGenerator() {
        try {
            Map param = new HashMap();
            param.put("queryRootMessages", 1);
            List<Message> latestMessages = messageMapper.queryList(param);

            for(Message m_:latestMessages){
                if (m_.getTitle().length() > 50) {
                    m_.setTitle(m_.getTitle().subSequence(0, 50)+"...");
                }
                m_.setUser(userService.query(m_.getCreate_user()));
            }
            Map map = new HashMap();
            map.put("topics", latestMessages);
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("freemarker/latesttopic.ftl");
            MyFreeMarker.generator(template, "latesttopic.html",map);
            log.info("latestTopics generator run.");
        }catch (Exception e) {
            log.error("latestTopics exception:" + e.toString());
        }
    }
}
